<template>
  <div class="user-management">
    <h2 class="page-title">用户管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="输入用户名或手机号搜索"
          clearable
          style="width: 300px"
          @keyup.enter="fetchUsers"
      >
        <template #prepend>
          <el-button icon="Search" @click="fetchUsers" />
        </template>
      </el-input>
      <el-button type="primary" @click="showAddDialog">新增用户</el-button>
      <el-button
          type="danger"
          :disabled="!selectedUsers.length"
          :loading="batchDeleting"
          @click="batchDeleteUsers"
      >
        批量删除
      </el-button>
    </div>
    <el-table
        ref="userTable"
        :data="users"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="userId"
        border
        height="calc(100vh - 300px)"
        v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userId" label="用户ID" width="80" sortable />
      <el-table-column prop="username" label="用户名" width="150" show-overflow-tooltip />
      <el-table-column prop="phoneNumber" label="手机号" width="150" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="isActive" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
            {{ scope.row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button
              type="danger"
              size="small"
              :loading="deletingUserId === scope.row.userId"
              @click="deleteUser(scope.row.userId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @update:current-page="pagination.currentPage = $event; fetchUsers()"
        @update:page-size="pagination.pageSize = $event; fetchUsers()"
        class="pagination"
    />

    <el-dialog
        :title="isEditMode ? '编辑用户' : '新增用户'"
        v-model="dialogVisible"
        width="500px"
        @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="passwordHash" v-if="!isEditMode">
          <el-input v-model="form.passwordHash" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="form.isActive" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'UserManagement',
  data() {
    return {
      users: [],
      searchQuery: '',
      selectedUsers: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      deletingUserId: null,
      batchDeleting: false,
      dialogVisible: false,
      isEditMode: false,
      submitting: false,
      form: {
        userId: null,
        username: '',
        phoneNumber: '',
        passwordHash: '',
        isActive: 1,
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phoneNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        passwordHash: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers() {
      this.loading = true;
      try {
        const response = await axios.get('/users/list', {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          params: {
            page: this.pagination.currentPage,
            size: this.pagination.pageSize,
            query: this.searchQuery,
          },
        });
        console.log('用户数据:', response.data);
        // 适配后端返回的数组格式，临时推算 total
        this.users = Array.isArray(response.data) ? response.data : response.data.list || [];
        this.pagination.total = response.data.total || this.users.length; // 如果后端未返回 total，临时使用数组长度
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败，请检查权限或网络');
      } finally {
        this.loading = false;
      }
    },

    async deleteUser(userId) {
      this.$confirm('确定要删除此用户吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.deletingUserId = userId;
        try {
          await axios.delete(`/users/delete/${userId}`, {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          });
          this.$message.success('删除用户成功');
          this.fetchUsers();
        } catch (error) {
          this.$message.error('删除用户失败，请重试');
        } finally {
          this.deletingUserId = null;
        }
      });
    },

    async batchDeleteUsers() {
      this.$confirm(`确定要删除 ${this.selectedUsers.length} 个选中的用户吗？删除后不可恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.batchDeleting = true;
        try {
          await Promise.all(
              this.selectedUsers.map(userId =>
                  axios.delete(`/users/delete/${userId}`, {
                    headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
                  })
              )
          );
          this.$message.success('批量删除用户成功');
          this.fetchUsers();
        } catch (error) {
          this.$message.error('批量删除用户失败，请重试');
        } finally {
          this.batchDeleting = false;
        }
      });
    },

    showAddDialog() {
      this.isEditMode = false;
      this.dialogVisible = true;
    },

    showEditDialog(user) {
      this.isEditMode = true;
      this.form = { ...user, passwordHash: '' };
      this.dialogVisible = true;
    },

    submitForm() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          this.submitting = true;
          try {
            if (this.isEditMode) {
              await axios.put(`/users/update/${this.form.userId}`, this.form, {
                headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
              });
              this.$message.success('更新用户成功');
            } else {
              await axios.post('/users/add', this.form, {
                headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
              });
              this.$message.success('新增用户成功');
            }
            this.dialogVisible = false;
            this.fetchUsers();
          } catch (error) {
            this.$message.error(this.isEditMode ? '更新用户失败' : '新增用户失败');
          } finally {
            this.submitting = false;
          }
        }
      });
    },

    resetForm() {
      this.form = { userId: null, username: '', phoneNumber: '', passwordHash: '', isActive: 1 };
      this.$refs.userForm.resetFields();
    },

    handleSelectionChange(val) {
      this.selectedUsers = val.map(row => row.userId);
    },

    formatDate(date) {
      return date ? new Date(date).toLocaleString('zh-CN', { hour12: false }) : '-';
    },
  },
};
</script>

<style scoped>
.user-management {
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  min-height: calc(100vh - 96px);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.el-table th {
  background-color: #f8fafc;
  color: #1f2937;
  font-weight: 600;
}

.el-table td {
  color: #4b5563;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}

.el-button--primary {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.el-button--primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

.el-button--danger {
  background-color: #ef4444;
  border-color: #ef4444;
}

.el-button--danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-dialog {
  border-radius: 8px;
}
</style>